import { uploadImage } from "@/api/upload";
import ImagePicker from "@/components/ImagePicker";
import { Button, Form, Input, Toast, View } from "@ant-design/react-native";
import { useState } from "react";
import { StyleSheet } from "react-native";
import { SafeAreaView } from "react-native-safe-area-context";

export default function AddScreen() {
  const [loading, setLoading] = useState(false);
  const [image, setImage] = useState("");
  const [toastApi, contextHolder] = Toast.useToast();
  const handleSubmit = () => {};

  const handleImageChange = (uri: string) => {
    handleUploadImage(uri);
  };

  const handleUploadImage = (uri: string) => {
    const formData = new FormData();
    formData.append("image", {
      uri: uri,
      type: "image/png",
      name: "image",
    } as any);

    uploadImage(formData)
      .then((res) => {
        setImage(res.data.data.imageUrl);
        console.log(res.data.data.imageUrl, "res.data.data.imageUrl");
        toastApi.success("上传成功");
      })
      .catch((err) => {
        console.log(err);
        toastApi.fail("上传失败");
      });
  };

  return (
    <SafeAreaView>
      {contextHolder}
      <View style={styles.container}>
        <Form>
          <Form.Item label="标题" name="title">
            <Input />
          </Form.Item>

          <Form.Item label="内容" name="content">
            <Input.TextArea
              placeholder="请输入内容"
              style={{ height: 200 }}
              numberOfLines={10}
            />
          </Form.Item>
          <Form.Item label="图片" name="image">
            <ImagePicker
              onChange={(image) => handleImageChange(image)}
              value={image}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onPress={handleSubmit} loading={loading}>
              发布
            </Button>
          </Form.Item>
        </Form>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 16,
    margin: 16,
    borderRadius: 16,
    backgroundColor: "#fff",
  },
});
